document.addEventListener('DOMContentLoaded', function() {
    console.log('=== Dashboard页面加载 ===');
    
    // 全局变量
    const API_BASE_URL = 'http://localhost:8080/userapi';
    let currentUser = null;

    // 工具函数
    const utils = {
        // 获取token
        getToken() {
            // 使用模拟token进行测试
            return 'mock-token-for-testing';
        },

        // 获取当前用户ID
        async getCurrentUserId() {
            const user = JSON.parse(localStorage.getItem('user') || sessionStorage.getItem('user') || '{}');
            
            // 如果有存储的用户信息，直接使用userId
            if (user.userId) {
                console.log('使用存储的用户ID:', user.userId);
                console.log('当前用户信息:', user);
                return user.userId;
            }
            
            // 如果没有用户信息，尝试根据手机号查找用户
            const phone = user.phone;
            if (phone) {
                console.log('根据手机号查找用户:', phone);
                try {
                    const response = await fetch(`${API_BASE_URL}/users/phone/${phone}`, {
                        headers: {
                            'Content-Type': 'application/json'
                        }
                    });
                    
                    if (response.ok) {
                        const data = await response.json();
                        const userId = data.data.userId;
                        console.log('通过API找到用户ID:', userId);
                        
                        // 更新存储的用户信息
                        const updatedUser = { ...user, userId: userId };
                        if (localStorage.getItem('user')) {
                            localStorage.setItem('user', JSON.stringify(updatedUser));
                        } else if (sessionStorage.getItem('user')) {
                            sessionStorage.setItem('user', JSON.stringify(updatedUser));
                        }
                        
                        return userId;
                    }
                } catch (error) {
                    console.error('根据手机号获取用户ID失败:', error);
                }
            }
            
            // 如果都没有，使用默认值
            console.log('使用默认用户ID: U000000001');
            return 'U000000001';
        },

        // 检查是否已登录
        checkAuth() {
            const token = localStorage.getItem('token') || sessionStorage.getItem('token');
            const user = JSON.parse(localStorage.getItem('user') || sessionStorage.getItem('user') || '{}');
            
            console.log('=== Dashboard认证检查 ===');
            console.log('localStorage token:', localStorage.getItem('token'));
            console.log('sessionStorage token:', sessionStorage.getItem('token'));
            console.log('最终使用的token:', token);
            console.log('用户信息:', user);
            
            if (!token) {
                console.log('❌ 没有找到token，跳转到登录页面');
                window.location.href = 'login.html';
                return false;
            }
            
            // 检查token格式
            if (!token.includes('.')) {
                console.log('❌ Token格式不正确，跳转到登录页面');
                window.location.href = 'login.html';
                return false;
            }
            
            console.log('✅ Token检查通过');
            return true;
        },

        // 显示加载状态
        showLoading() {
            const loading = document.createElement('div');
            loading.className = 'loading-overlay';
            loading.innerHTML = '<div class="loading-spinner"></div>';
            document.body.appendChild(loading);
        },

        // 隐藏加载状态
        hideLoading() {
            const loading = document.querySelector('.loading-overlay');
            if (loading) {
                loading.remove();
            }
        },

        // 显示消息提示
        showMessage(message, isError = false) {
            const messageDiv = document.createElement('div');
            messageDiv.className = `message ${isError ? 'error' : 'success'}`;
            messageDiv.textContent = message;
            document.body.appendChild(messageDiv);
            setTimeout(() => messageDiv.remove(), 3000);
        },

        // 验证邮箱
        validateEmail(email) {
            return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
        },

        // 验证游戏UID
        validateGameUid(uid) {
            return /^\d{8,10}$/.test(uid);
        },

        // 处理API响应
        async handleResponse(response) {
            console.log('响应状态:', response.status);
            console.log('响应头:', response.headers);
            
            if (!response.ok) {
                const errorText = await response.text();
                console.log('错误响应内容:', errorText);
                
                let errorData;
                try {
                    errorData = JSON.parse(errorText);
                } catch (e) {
                    console.log('JSON解析失败:', e);
                    errorData = { error: '服务器响应错误' };
                }
                throw new Error(errorData.error || '请求失败');
            }
            
            const contentType = response.headers.get('content-type');
            console.log('Content-Type:', contentType);
            
            if (contentType && contentType.includes('application/json')) {
                const data = await response.json();
                console.log('JSON响应数据:', data);
                return data;
            } else {
                const text = await response.text();
                console.log('文本响应数据:', text);
                try {
                    return JSON.parse(text);
                } catch (e) {
                    console.log('文本解析为JSON失败:', e);
                    throw new Error('服务器返回了无效的JSON数据');
                }
            }
        }
    };

    // 用户信息管理
    const userManager = {
        // 获取用户信息
        async fetchUserProfile() {
            try {
                utils.showLoading();
                console.log('开始获取用户信息...');
                
                const userId = await utils.getCurrentUserId();
                const response = await fetch(`${API_BASE_URL}/users/profile/${userId}`, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                console.log('获取用户信息响应:', response);
                const data = await utils.handleResponse(response);
                
                // 处理user模块的响应格式
                if (data.user && data.privacy) {
                    // 合并用户信息和隐私设置
                    currentUser = { ...data.user, ...data.privacy };
                } else {
                    currentUser = data;
                }
                
                this.updateUI(currentUser);
                this.populateForm(currentUser);
                
                // 初始化等级显示（使用模拟数据）
                this.initLevelDisplay();
                
                // 获取用户游戏角色
                await this.fetchUserCharacters();
            } catch (error) {
                console.error('获取用户信息失败:', error);
                utils.showMessage(error.message, true);
            } finally {
                utils.hideLoading();
            }
        },

        // 获取用户游戏角色
        async fetchUserCharacters() {
            try {
                const userId = await utils.getCurrentUserId();
                const response = await fetch(`${API_BASE_URL}/users/profile/${userId}/characters`, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                if (response.ok) {
                    const characters = await response.json();
                    this.renderCharacters(characters);
                }
            } catch (error) {
                console.error('获取游戏角色失败:', error);
            }
        },

        // 渲染游戏角色列表
        renderCharacters(characters) {
            const charactersContainer = document.querySelector('.characters-list');
            if (!charactersContainer) return;

            if (characters.length === 0) {
                charactersContainer.innerHTML = '<p class="no-characters">暂无游戏角色</p>';
                return;
            }

            charactersContainer.innerHTML = characters.map(character => `
                <div class="character-card" data-character-id="${character.characterId}">
                    <div class="character-avatar">
                        <img src="${character.characterAvatar || 'images/default-character.png'}" alt="${character.characterName}">
                    </div>
                    <div class="character-info">
                        <h4>${character.characterName}</h4>
                        <p>等级: ${character.characterLevel}</p>
                        <p>稀有度: ${character.characterRarity}</p>
                        <p>元素: ${character.characterElement}</p>
                        <p>命途: ${character.characterPath}</p>
                    </div>
                    <div class="character-actions">
                        <button class="btn-edit-character" onclick="userManager.editCharacter('${character.characterId}')">
                            <i class="fas fa-edit"></i>
                        </button>
                        <button class="btn-delete-character" onclick="userManager.deleteCharacter('${character.characterId}')">
                            <i class="fas fa-trash"></i>
                        </button>
                    </div>
                </div>
            `).join('');
        },

        // 编辑游戏角色
        async editCharacter(characterId) {
            try {
                const userId = await utils.getCurrentUserId();
                const response = await fetch(`${API_BASE_URL}/users/profile/${userId}/characters/${characterId}`, {
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                if (response.ok) {
                    const character = await response.json();
                    this.populateCharacterForm(character);
                    modalManager.showModal(document.getElementById('editCharacterModal'));
                }
            } catch (error) {
                console.error('获取角色信息失败:', error);
                utils.showMessage('获取角色信息失败', true);
            }
        },

        // 删除游戏角色
        async deleteCharacter(characterId) {
            if (!confirm('确定要删除这个角色吗？')) return;
            
            try {
                const userId = await utils.getCurrentUserId();
                const response = await fetch(`${API_BASE_URL}/users/profile/${userId}/characters/${characterId}`, {
                    method: 'DELETE',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });
                
                if (response.ok) {
                    utils.showMessage('角色删除成功');
                    await this.fetchUserCharacters();
                } else {
                    const error = await response.json();
                    utils.showMessage(error.message || '删除失败', true);
                }
            } catch (error) {
                console.error('删除角色失败:', error);
                utils.showMessage('删除角色失败', true);
            }
        },

        // 填充角色表单
        populateCharacterForm(character) {
            document.getElementById('editCharacterName').value = character.characterName || '';
            document.getElementById('editCharacterLevel').value = character.characterLevel || '';
            document.getElementById('editCharacterRarity').value = character.characterRarity || '';
            document.getElementById('editCharacterElement').value = character.characterElement || '';
            document.getElementById('editCharacterPath').value = character.characterPath || '';
            document.getElementById('editCharacterAvatar').value = character.characterAvatar || '';
            document.getElementById('editCharacterConstellation').value = character.characterConstellation || '';
            document.getElementById('editCharacterEidolon').value = character.characterEidolon || '';
            document.getElementById('editCharacterSkillLevel').value = character.characterSkillLevel || '';
            document.getElementById('editCharacterId').value = character.characterId || '';
        },

        // 初始化等级显示（使用模拟数据）
        initLevelDisplay() {
            // 模拟等级数据
            const mockLevelData = {
                level: 1,
                experience: 0,
                experienceToNext: 100,
                levelName: '新手',
                permissions: ['post_create', 'comment_create'],
                isMaxLevel: false
            };
            
            this.updateLevelUI(mockLevelData);
        },

        // 更新等级UI显示
        updateLevelUI(levelData) {
            console.log('更新等级UI显示:', levelData);
            
            // 更新个人信息卡片中的等级显示
            const levelNumber = document.querySelector('.level-number');
            const levelName = document.querySelector('.level-name');
            const expProgress = document.querySelector('.exp-progress');
            const expText = document.querySelector('.exp-text');
            
            if (levelNumber) levelNumber.textContent = levelData.level;
            if (levelName) levelName.textContent = levelData.levelName;
            
            // 计算经验值进度百分比
            const currentExp = levelData.experience;
            const nextLevelExp = levelData.experienceToNext > 0 ? 
                levelData.experience + levelData.experienceToNext : 
                levelData.experience;
            const progressPercent = nextLevelExp > 0 ? (currentExp / nextLevelExp) * 100 : 0;
            
            if (expProgress) expProgress.style.width = `${Math.min(progressPercent, 100)}%`;
            if (expText) expText.textContent = `${currentExp}/${nextLevelExp} 经验`;
            
            // 更新等级与权限卡片中的详细显示
            const levelNumberLarge = document.querySelector('.level-number-large');
            const levelNameLarge = document.querySelector('.level-name-large');
            const currentExpEl = document.querySelector('.current-exp');
            const nextLevelExpEl = document.querySelector('.next-level-exp');
            const expProgressLarge = document.querySelector('.exp-progress-large');
            const expToNext = document.querySelector('.exp-to-next');
            
            if (levelNumberLarge) levelNumberLarge.textContent = levelData.level;
            if (levelNameLarge) levelNameLarge.textContent = levelData.levelName;
            if (currentExpEl) currentExpEl.textContent = currentExp;
            if (nextLevelExpEl) nextLevelExpEl.textContent = nextLevelExp;
            if (expProgressLarge) expProgressLarge.style.width = `${Math.min(progressPercent, 100)}%`;
            if (expToNext) {
                if (levelData.isMaxLevel) {
                    expToNext.textContent = '已达到最高等级';
                } else {
                    expToNext.textContent = `距离下一级还需 ${levelData.experienceToNext} 经验`;
                }
            }
            
            // 更新权限显示
            this.updatePermissionsUI(levelData.permissions);
        },

        // 更新权限UI显示
        updatePermissionsUI(permissions) {
            const permissionItems = document.querySelectorAll('.permission-item');
            
            // 权限映射
            const permissionMap = {
                'post_create': '发布帖子',
                'comment_create': '发表评论',
                'post_edit': '编辑帖子',
                'image_upload': '上传图片',
                'video_upload': '上传视频',
                'post_pin': '帖子置顶',
                'moderate_comments': '评论管理',
                'moderate_posts': '帖子管理',
                'manage_users': '用户管理',
                'system_settings': '系统设置'
            };
            
            permissionItems.forEach(item => {
                const permissionText = item.querySelector('span').textContent;
                const permissionKey = Object.keys(permissionMap).find(key => 
                    permissionMap[key] === permissionText
                );
                
                if (permissionKey) {
                    const hasPermission = permissions.includes('all') || permissions.includes(permissionKey);
                    const icon = item.querySelector('i');
                    
                    if (hasPermission) {
                        item.classList.remove('disabled');
                        icon.className = 'fas fa-check-circle';
                    } else {
                        item.classList.add('disabled');
                        icon.className = 'fas fa-times-circle';
                    }
                }
            });
        },

        // 更新用户信息
        async updateProfile(formData) {
            try {
                utils.showLoading();
                console.log('开始更新用户信息...');
                console.log('更新数据:', formData);
                
                const userId = await utils.getCurrentUserId();
                const response = await fetch(`${API_BASE_URL}/users/profile/${userId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                });
                
                console.log('更新用户信息响应:', response);
                const data = await utils.handleResponse(response);
                currentUser = data;
                this.updateUI(data);
                return true;
            } catch (error) {
                console.error('更新用户信息失败:', error);
                utils.showMessage(error.message, true);
                return false;
            } finally {
                utils.hideLoading();
            }
        },

        // 更新隐私设置
        async updatePrivacySettings(formData) {
            try {
                utils.showLoading();
                console.log('开始更新隐私设置...');
                console.log('隐私设置数据:', formData);
                
                const userId = await utils.getCurrentUserId();
                const response = await fetch(`${API_BASE_URL}/users/profile/${userId}/privacy`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                });
                
                console.log('更新隐私设置响应:', response);
                const data = await utils.handleResponse(response);
                
                // 更新当前用户的隐私设置
                currentUser = { ...currentUser, ...data };
                this.updateUI(currentUser);
                
                utils.showMessage('隐私设置更新成功');
                return true;
            } catch (error) {
                console.error('更新隐私设置失败:', error);
                utils.showMessage(error.message, true);
                return false;
            } finally {
                utils.hideLoading();
            }
        },

        // 添加游戏角色
        async addCharacter(formData) {
            try {
                utils.showLoading();
                console.log('开始添加游戏角色...');
                console.log('角色数据:', formData);
                
                const userId = await utils.getCurrentUserId();
                const response = await fetch(`${API_BASE_URL}/users/profile/${userId}/characters`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                });
                
                console.log('添加角色响应:', response);
                const data = await utils.handleResponse(response);
                
                utils.showMessage('角色添加成功');
                await this.fetchUserCharacters();
                return true;
            } catch (error) {
                console.error('添加角色失败:', error);
                utils.showMessage(error.message, true);
                return false;
            } finally {
                utils.hideLoading();
            }
        },

        // 更新游戏角色
        async updateCharacter(formData) {
            try {
                utils.showLoading();
                console.log('开始更新游戏角色...');
                console.log('角色数据:', formData);
                
                const userId = await utils.getCurrentUserId();
                const characterId = formData.characterId;
                delete formData.characterId; // 从请求体中移除characterId
                
                const response = await fetch(`${API_BASE_URL}/users/profile/${userId}/characters/${characterId}`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(formData)
                });
                
                console.log('更新角色响应:', response);
                const data = await utils.handleResponse(response);
                
                utils.showMessage('角色更新成功');
                await this.fetchUserCharacters();
                return true;
            } catch (error) {
                console.error('更新角色失败:', error);
                utils.showMessage(error.message, true);
                return false;
            } finally {
                utils.hideLoading();
            }
        },

        // 更新UI显示
        updateUI(data) {
            console.log('更新UI显示:', data);
            
            // 更新头像
            const avatarImages = document.querySelectorAll('.user-avatar img, .profile-avatar img, .dropdown-header img');
            avatarImages.forEach(img => {
                img.src = data.avatar || 'images/default-avatar.png';
            });

            // 更新用户信息
            document.querySelectorAll('.profile-info h3').forEach(el => {
                el.textContent = data.nickname || '用户名';
            });
            document.querySelector('.user-id').textContent = `UID: ${data.gameUid || '未绑定'}`;

            // 更新游戏账号信息
            if (data.gameUid) {
                const accountList = document.querySelector('.account-list');
                if (accountList) {
                    accountList.innerHTML = `
                        <div class="account-item">
                            <div class="account-info">
                                <span class="game-uid">UID: ${data.gameUid}</span>
                            </div>
                        </div>
                    `;
                }
            }
        },

        // 填充表单数据
        populateForm(data) {
            console.log('填充表单数据:', data);
            
            document.getElementById('nickname').value = data.nickname || '';
            document.getElementById('gender').value = data.gender || '0';
            document.getElementById('email').value = data.email || '';
            document.getElementById('selectedAvatar').value = data.avatar || '';

            // 设置当前头像为选中状态
            const avatarOptions = document.querySelectorAll('.avatar-option');
            avatarOptions.forEach(option => {
                option.classList.remove('selected');
                if (option.dataset.avatar === data.avatar) {
                    option.classList.add('selected');
                }
            });

            // 填充隐私设置表单
            document.getElementById('showProfile').checked = data.showProfile !== false;
            document.getElementById('showGameProgress').checked = data.showGameProgress !== false;
            document.getElementById('showCharacters').checked = data.showCharacters !== false;
            document.getElementById('showOnlineStatus').checked = data.showOnlineStatus !== false;
            document.getElementById('showLastLoginTime').checked = data.showLastLoginTime !== false;
        }
    };

    // 模态窗口管理
    const modalManager = {
        showModal(modal) {
            if (!modal) return;
            modal.classList.add('show');
            document.body.style.overflow = 'hidden';
        },

        hideModal(modal) {
            if (!modal) return;
            modal.classList.remove('show');
            document.body.style.overflow = '';
        }
    };

    // 头像选择管理
    const avatarManager = {
        init() {
            const avatarOptions = document.querySelectorAll('.avatar-option');
            avatarOptions.forEach(option => {
                option.addEventListener('click', () => {
                    // 移除其他选中状态
                    avatarOptions.forEach(opt => opt.classList.remove('selected'));
                    // 添加当前选中状态
                    option.classList.add('selected');
                    // 更新隐藏输入框的值
                    document.getElementById('selectedAvatar').value = option.dataset.avatar;
                });
            });
        }
    };

    // 表单处理
    const formManager = {
        init() {
            this.initEditProfileForm();
            this.initPrivacySettingsForm();
            this.initAddCharacterForm();
            this.initEditCharacterForm();
        },

        initEditProfileForm() {
            const form = document.getElementById('editProfileForm');
            if (!form) return;

            form.addEventListener('submit', async (event) => {
                event.preventDefault();
                
                const formData = {
                    nickname: document.getElementById('nickname').value,
                    gender: parseInt(document.getElementById('gender').value),
                    email: document.getElementById('email').value,
                    avatar: document.getElementById('selectedAvatar').value
                };

                const success = await userManager.updateProfile(formData);
                if (success) {
                    modalManager.hideModal(document.getElementById('editProfileModal'));
                }
            });
        },

        initPrivacySettingsForm() {
            const form = document.getElementById('privacySettingsForm');
            if (!form) return;

            form.addEventListener('submit', async (event) => {
                event.preventDefault();
                
                const formData = {
                    showProfile: document.getElementById('showProfile').checked,
                    showGameProgress: document.getElementById('showGameProgress').checked,
                    showCharacters: document.getElementById('showCharacters').checked,
                    showOnlineStatus: document.getElementById('showOnlineStatus').checked,
                    showLastLoginTime: document.getElementById('showLastLoginTime').checked
                };

                const success = await userManager.updatePrivacySettings(formData);
                if (success) {
                    modalManager.hideModal(document.getElementById('privacySettingsModal'));
                }
            });
        },

        initAddCharacterForm() {
            const form = document.getElementById('addCharacterForm');
            if (!form) return;

            form.addEventListener('submit', async (event) => {
                event.preventDefault();
                
                const formData = {
                    characterName: document.getElementById('characterName').value,
                    characterLevel: parseInt(document.getElementById('characterLevel').value),
                    characterRarity: document.getElementById('characterRarity').value,
                    characterElement: document.getElementById('characterElement').value,
                    characterPath: document.getElementById('characterPath').value,
                    characterAvatar: document.getElementById('characterAvatar').value,
                    characterConstellation: parseInt(document.getElementById('characterConstellation').value) || 0,
                    characterEidolon: parseInt(document.getElementById('characterEidolon').value) || 0,
                    characterSkillLevel: parseInt(document.getElementById('characterSkillLevel').value) || 1
                };

                const success = await userManager.addCharacter(formData);
                if (success) {
                    modalManager.hideModal(document.getElementById('addCharacterModal'));
                    form.reset();
                }
            });
        },

        initEditCharacterForm() {
            const form = document.getElementById('editCharacterForm');
            if (!form) return;

            form.addEventListener('submit', async (event) => {
                event.preventDefault();
                
                const formData = {
                    characterId: document.getElementById('editCharacterId').value,
                    characterName: document.getElementById('editCharacterName').value,
                    characterLevel: parseInt(document.getElementById('editCharacterLevel').value),
                    characterRarity: document.getElementById('editCharacterRarity').value,
                    characterElement: document.getElementById('editCharacterElement').value,
                    characterPath: document.getElementById('editCharacterPath').value,
                    characterAvatar: document.getElementById('editCharacterAvatar').value,
                    characterConstellation: parseInt(document.getElementById('editCharacterConstellation').value) || 0,
                    characterEidolon: parseInt(document.getElementById('editCharacterEidolon').value) || 0,
                    characterSkillLevel: parseInt(document.getElementById('editCharacterSkillLevel').value) || 1
                };

                const success = await userManager.updateCharacter(formData);
                if (success) {
                    modalManager.hideModal(document.getElementById('editCharacterModal'));
                }
            });
        }
    };

    // 帖子管理
    const postManager = {
        currentPage: 1,
        currentSort: 'latest',
        postsPerPage: 10,

        // 获取用户帖子 - 暂时禁用，因为接口不存在
        async fetchUserPosts(page = 1, sort = 'latest') {
            try {
                console.log('帖子管理功能暂时禁用，接口待实现');
                this.showEmptyState();
                return { data: [] };
            } catch (error) {
                console.error('获取用户帖子失败:', error);
                this.showEmptyState();
            }
        },

        // 渲染帖子列表
        renderPosts(data) {
            const postsList = document.querySelector('.posts-list');
            if (!postsList) return;

            if (!data.data || data.data.length === 0) {
                this.showEmptyState();
                return;
            }

            const postsHTML = data.data.map(post => this.createPostHTML(post)).join('');
            postsList.innerHTML = postsHTML;

            // 绑定帖子操作事件
            this.bindPostActions();
        },

        // 创建帖子HTML
        createPostHTML(post) {
            const createTime = new Date(post.create_time).toLocaleString('zh-CN');
            const content = post.content.length > 150 ? post.content.substring(0, 150) + '...' : post.content;
            
            return `
                <div class="post-item" data-post-id="${post.post_id}">
                    <div class="post-header">
                        <h4 class="post-title">${post.title}</h4>
                        <div class="post-actions-menu">
                            <button class="post-action-btn edit-post-btn" data-post-id="${post.post_id}">
                                <i class="fas fa-edit"></i> 编辑
                            </button>
                            <button class="post-action-btn delete-post-btn" data-post-id="${post.post_id}">
                                <i class="fas fa-trash"></i> 删除
                            </button>
                        </div>
                    </div>
                    <div class="post-meta">
                        <span><i class="fas fa-tag"></i> ${post.post_type}</span>
                        <span><i class="fas fa-folder"></i> ${post.category}</span>
                        <span><i class="fas fa-clock"></i> ${createTime}</span>
                    </div>
                    <div class="post-content">${content}</div>
                    <div class="post-stats">
                        <span><i class="fas fa-eye"></i> ${post.view_count || 0}</span>
                        <span><i class="fas fa-heart"></i> ${post.like_count || 0}</span>
                        <span><i class="fas fa-comment"></i> ${post.comment_count || 0}</span>
                    </div>
                </div>
            `;
        },

        // 显示空状态
        showEmptyState() {
            const postsList = document.querySelector('.posts-list');
            if (!postsList) return;

            postsList.innerHTML = `
                <div class="empty-posts">
                    <i class="fas fa-file-alt"></i>
                    <p>帖子管理功能正在开发中</p>
                    <p>请先使用用户档案和游戏角色管理功能</p>
                </div>
            `;
        },

        // 绑定帖子操作事件
        bindPostActions() {
            // 暂时禁用帖子操作
        },

        // 编辑帖子
        async editPost(postId) {
            console.log('帖子编辑功能暂时禁用');
        },

        // 填充编辑表单
        populateEditForm(post) {
            console.log('帖子编辑表单功能暂时禁用');
        },

        // 确认删除帖子
        confirmDeletePost(postId) {
            console.log('帖子删除功能暂时禁用');
        },

        // 删除帖子
        async deletePost(postId) {
            console.log('帖子删除功能暂时禁用');
        },

        // 更新帖子
        async updatePost(formData) {
            console.log('帖子更新功能暂时禁用');
        },

        // 更新分页
        updatePagination(data) {
            console.log('帖子分页功能暂时禁用');
        },

        // 初始化
        init() {
            console.log('初始化帖子管理...');
            this.fetchUserPosts();
        }
    };

    // 修改密码功能管理器
    const passwordManager = {
        // 初始化修改密码功能
        init() {
            this.initChangePasswordForm();
            this.bindChangePasswordMenu();
        },

        // 绑定修改密码菜单
        bindChangePasswordMenu() {
            const changePasswordMenu = document.getElementById('changePasswordMenu');
            if (changePasswordMenu) {
                changePasswordMenu.addEventListener('click', (e) => {
                    e.preventDefault();
                    modalManager.showModal(document.getElementById('changePasswordModal'));
                    this.resetForm();
                });
            }
        },

        // 初始化修改密码表单
        initChangePasswordForm() {
            const form = document.getElementById('changePasswordForm');
            if (!form) return;

            // 绑定表单提交
            form.addEventListener('submit', async (e) => {
                e.preventDefault();
                await this.submitChangePassword();
            });

            // 绑定密码显示/隐藏切换
            document.querySelectorAll('.toggle-password').forEach(toggle => {
                toggle.addEventListener('click', (e) => {
                    const input = e.target.previousElementSibling;
                    const type = input.getAttribute('type') === 'password' ? 'text' : 'password';
                    input.setAttribute('type', type);
                    e.target.classList.toggle('fa-eye');
                    e.target.classList.toggle('fa-eye-slash');
                });
            });

            // 绑定新密码强度检测
            const newPasswordInput = document.getElementById('newPassword');
            if (newPasswordInput) {
                newPasswordInput.addEventListener('input', (e) => {
                    this.checkPasswordStrength(e.target.value);
                    this.validatePasswordRequirements(e.target.value);
                });
            }

            // 绑定确认密码验证
            const confirmPasswordInput = document.getElementById('confirmNewPassword');
            if (confirmPasswordInput) {
                confirmPasswordInput.addEventListener('input', (e) => {
                    this.validateConfirmPassword(e.target.value);
                });
            }
        },

        // 检查密码强度
        checkPasswordStrength(password) {
            const strengthFill = document.getElementById('strengthFill');
            const strengthText = document.getElementById('strengthText');
            
            if (!strengthFill || !strengthText) return;

            let strength = 0;
            let strengthClass = 'weak';
            let strengthLabel = '弱';

            // 长度检查
            if (password.length >= 6) strength += 25;
            if (password.length >= 8) strength += 25;
            
            // 字符类型检查
            if (/[a-zA-Z]/.test(password)) strength += 25;
            if (/[0-9]/.test(password)) strength += 25;
            if (/[^a-zA-Z0-9]/.test(password)) strength += 25;

            // 确定强度等级
            if (strength >= 100) {
                strengthClass = 'very-strong';
                strengthLabel = '非常强';
            } else if (strength >= 75) {
                strengthClass = 'strong';
                strengthLabel = '强';
            } else if (strength >= 50) {
                strengthClass = 'medium';
                strengthLabel = '中等';
            } else {
                strengthClass = 'weak';
                strengthLabel = '弱';
            }

            // 更新UI
            strengthFill.className = `strength-fill ${strengthClass}`;
            strengthText.textContent = `密码强度：${strengthLabel}`;
        },

        // 验证密码要求
        validatePasswordRequirements(password) {
            const requirements = {
                length: password.length >= 6,
                letter: /[a-zA-Z]/.test(password),
                number: /[0-9]/.test(password),
                special: /[^a-zA-Z0-9]/.test(password)
            };

            // 更新要求显示
            Object.keys(requirements).forEach(req => {
                const element = document.getElementById(`req-${req}`);
                if (element) {
                    if (req === 'special') {
                        // 特殊字符是可选的
                        element.classList.remove('invalid');
                        element.classList.add(requirements[req] ? 'valid' : 'optional');
                    } else {
                        element.classList.remove('invalid', 'optional');
                        element.classList.add(requirements[req] ? 'valid' : 'invalid');
                    }
                }
            });
        },

        // 验证确认密码
        validateConfirmPassword(confirmPassword) {
            const newPassword = document.getElementById('newPassword').value;
            const errorElement = document.getElementById('confirmNewPasswordError');
            
            if (!errorElement) return;

            if (confirmPassword !== newPassword) {
                this.showError('confirmNewPasswordError', '两次输入的密码不一致');
            } else {
                this.hideError('confirmNewPasswordError');
            }
        },

        // 显示错误信息
        showError(elementId, message) {
            const element = document.getElementById(elementId);
            if (element) {
                element.textContent = message;
                element.classList.add('show');
            }
        },

        // 隐藏错误信息
        hideError(elementId) {
            const element = document.getElementById(elementId);
            if (element) {
                element.classList.remove('show');
            }
        },

        // 重置表单
        resetForm() {
            const form = document.getElementById('changePasswordForm');
            if (form) {
                form.reset();
                this.hideAllErrors();
                this.resetPasswordStrength();
            }
        },

        // 隐藏所有错误信息
        hideAllErrors() {
            ['oldPasswordError', 'newPasswordError', 'confirmNewPasswordError'].forEach(id => {
                this.hideError(id);
            });
        },

        // 重置密码强度显示
        resetPasswordStrength() {
            const strengthFill = document.getElementById('strengthFill');
            const strengthText = document.getElementById('strengthText');
            
            if (strengthFill) {
                strengthFill.className = 'strength-fill';
            }
            if (strengthText) {
                strengthText.textContent = '密码强度：弱';
            }
        },

        // 提交修改密码请求
        async submitChangePassword() {
            const submitBtn = document.querySelector('#changePasswordForm button[type="submit"]');
            const oldPassword = document.getElementById('oldPassword').value;
            const newPassword = document.getElementById('newPassword').value;
            const confirmPassword = document.getElementById('confirmNewPassword').value;

            // 验证表单
            if (!this.validateForm(oldPassword, newPassword, confirmPassword)) {
                return;
            }

            // 显示加载状态
            submitBtn.classList.add('loading');
            submitBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 修改中...';

            try {
                // 获取用户信息
                const user = JSON.parse(localStorage.getItem('user') || sessionStorage.getItem('user') || '{}');
                const userId = user.userId || user.id || user.user_id || 'U000000001';

                if (!userId) {
                    throw new Error('用户信息获取失败，请重新登录');
                }

                // 发送修改密码请求到user模块后端
                const response = await fetch(`http://localhost:8080/api/users/${userId}/password?oldPassword=${encodeURIComponent(oldPassword)}&newPassword=${encodeURIComponent(newPassword)}`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    }
                });

                const data = await response.json();

                if (response.ok) {
                    // 修改成功
                    utils.showMessage('密码修改成功！', false);
                    modalManager.hideModal(document.getElementById('changePasswordModal'));
                    
                    // 可选：修改成功后要求用户重新登录
                    if (confirm('密码修改成功！为了安全起见，建议重新登录。是否现在重新登录？')) {
                        localStorage.removeItem('user');
                        localStorage.removeItem('token');
                        sessionStorage.removeItem('user');
                        sessionStorage.removeItem('token');
                        window.location.href = 'login.html';
                    }
                } else {
                    // 修改失败
                    const errorMessage = data.message || '密码修改失败，请检查输入信息';
                    if (errorMessage.includes('原密码') || errorMessage.includes('当前密码')) {
                        this.showError('oldPasswordError', errorMessage);
                    } else {
                        this.showError('newPasswordError', errorMessage);
                    }
                }
            } catch (error) {
                console.error('修改密码失败:', error);
                utils.showMessage('网络错误，请稍后重试', true);
            } finally {
                // 恢复按钮状态
                submitBtn.classList.remove('loading');
                submitBtn.innerHTML = '<i class="fas fa-key"></i> 修改密码';
            }
        },

        // 验证表单
        validateForm(oldPassword, newPassword, confirmPassword) {
            let isValid = true;

            // 验证当前密码
            if (!oldPassword.trim()) {
                this.showError('oldPasswordError', '请输入当前密码');
                isValid = false;
            }

            // 验证新密码
            if (!newPassword.trim()) {
                this.showError('newPasswordError', '请输入新密码');
                isValid = false;
            } else if (newPassword.length < 6) {
                this.showError('newPasswordError', '新密码至少需要6位字符');
                isValid = false;
            } else if (!/[a-zA-Z]/.test(newPassword)) {
                this.showError('newPasswordError', '新密码必须包含字母');
                isValid = false;
            } else if (!/[0-9]/.test(newPassword)) {
                this.showError('newPasswordError', '新密码必须包含数字');
                isValid = false;
            }

            // 验证确认密码
            if (!confirmPassword.trim()) {
                this.showError('confirmNewPasswordError', '请确认新密码');
                isValid = false;
            } else if (confirmPassword !== newPassword) {
                this.showError('confirmNewPasswordError', '两次输入的密码不一致');
                isValid = false;
            }

            return isValid;
        }
    };

    // 显示模拟的经验历史数据
    function showMockExperienceHistory() {
        const historyList = document.querySelector('.history-list');
        if (!historyList) return;

        // 模拟经验历史数据
        const mockHistory = [
            {
                action: 'post_create',
                amount: 50,
                description: '发布帖子：新手攻略',
                create_time: '2024-01-15 14:30:00'
            },
            {
                action: 'daily_login',
                amount: 10,
                description: '每日登录奖励',
                create_time: '2024-01-15 09:00:00'
            },
            {
                action: 'profile_complete',
                amount: 20,
                description: '完善个人资料',
                create_time: '2024-01-14 16:20:00'
            },
            {
                action: 'game_uid_bind',
                amount: 30,
                description: '绑定游戏账号：12345678',
                create_time: '2024-01-14 10:15:00'
            }
        ];

        const actionNames = {
            'post_create': '发布帖子',
            'daily_login': '每日登录',
            'profile_complete': '完善资料',
            'game_uid_bind': '绑定游戏账号',
            'avatar_upload': '上传头像'
        };

        const historyHTML = mockHistory.map(item => `
            <div class="history-item">
                <div class="history-info">
                    <div class="history-action">${actionNames[item.action] || item.action}</div>
                    <div class="history-description">${item.description}</div>
                    <div class="history-time">${item.create_time}</div>
                </div>
                <div class="history-amount">+${item.amount}</div>
            </div>
        `).join('');

        historyList.innerHTML = historyHTML;
    }

    // 初始化
    async function init() {
        console.log('初始化Dashboard...');
        
        // 检查认证
        if (!utils.checkAuth()) {
            return;
        }
        
        // 获取用户信息
        await userManager.fetchUserProfile();
        
        // 初始化帖子管理
        postManager.init();
        
        // 绑定事件
        bindEvents();
    }

    // 检查认证
    function checkAuth(){
        console.log('=== Dashboard认证检查 ===');
        const token = utils.getToken();
        console.log('localStorage token:', localStorage.getItem('token'));
        console.log('sessionStorage token:', sessionStorage.getItem('token'));
        console.log('最终使用的token:', token);
        
        const user = JSON.parse(localStorage.getItem('user') || sessionStorage.getItem('user') || '{}');
        console.log('用户信息:', user);
        
        if (!token) {
            console.log('❌ 没有找到token，跳转到登录页面');
            window.location.href = 'login.html';
            return false;
        }
        
        console.log('✅ Token检查通过');
        return true;
    }

    // 启动应用
    init();
});